package com.roy.nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/4
 * @description: 启动一个服务端，多个客户端组成聊天室
 **/

public class ChatClient {
    private Selector selector;
    private SocketChannel socketChannel;

    ChatClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void connect() throws IOException {

        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("连接建立中。");
            }
        }
        System.out.println("服务端连接成功。连接端口："+socketChannel.getLocalAddress()+";等待输入内容。");
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            final String message = scanner.nextLine();
            if("q".equals(message)){
                socketChannel.close();
                System.exit(0);
            }
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        }
    }

    public void readInfo() {
        try {
            final int readChannelCount = selector.select();
            if (readChannelCount > 0) {
                final Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    final SelectionKey nextKey = iter.next();
                    if (nextKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) nextKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        socketChannel.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iter.remove();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        ChatClient chatClient = new ChatClient();
        new Thread(()->{
            System.out.println("启动监听");
            try{
                while(true){
                    chatClient.readInfo();
                    Thread.sleep(3000);
                }
            }catch (Exception e ){
                e.printStackTrace();
            }
        }).start();
        chatClient.connect();
    }
}
